function getStrFromArray(array) {
    let str = "";
    if (array == null)
        return "";
    for (let i = 0; i < array.length; i++) {
        str += (i != 0 ? "；" : "") + array[i];
    }
    return str;
}

function getStrFromJson(json) {
    let str = [];
    for (let i in json) {
        for (let j in json[i]) {
            str.push(json[i][j]);
        }
    }
    return str;
}

var getWordThread, stopThread;

function threadsSuspend(time, fun, end) {
        if (getWordThread != null && getWordThread.isAlive()) {
            getWordThread.interrupt();
        }
        if (stopThread != null && stopThread.isAlive())
            stopThread.interrupt();
    
    getWordThread = threads.start(function() {
        fun();
    });
    stopThread = threads.start(function() {
        sleep(time);
        if (getWordThread.isAlive()) {
            getWordThread.interrupt();
            if (end != null)
                end();
        }
    });
}

//网易源，更多释义
function getMoreMeaning(words) {
    if (words == "")
        return {
            trs: "",
        };

    let res;
    try {
        res = http.postJson("http://dict.youdao.com/jsonapi_s?le=&t=1608973762896&sign=534544f64b2073f6b975044912ac60ee&client=mobile&jsonversion=4&keyversion=20171115&userLabel=LEARNER,%20HIGHSCHOOL,%20CET4&abtest=1&keyfrom=mdict.9.0.6.android&vendor=tencent&mid=10&imei=2e48c18f-5e01-483d-8de5-faed3ee21a5d&model=RMX2121&ssid=%3Cunknown+ssid%3E&q=  " + String(words),
            dictsi = {
                "count": 0,
                "dicts": [
                    ["ec"]
                ]
            });
        res = res.body.json();
    } catch(e) {
        log("网络错误：" + e);
    };

    if (res == null || res.meta == null || res.meta.input != words)
        return {
            web_trans: "",
            exam_type: "",
            wfs: [],
            sentencepair: [],
            ee: [],
            synos: [],

        };

    var web_trans = "",
        wfs = [];

    var ec = res.ec;
    if (ec != null) {
        web_trans = getStrFromArray(ec.web_trans);

        var exam_type = "";
        if (ec.exam_type != null) {
            for (let i = 0; i < ec.exam_type.length; i++) {
                exam_type += (i == 0 ? "" : "/") + ec.exam_type[i];
            }
        }

        var word = res.ec.word;
        if (word != null) {
            wfs = getStrFromJson(word != null ? word.wfs : {});
        }
    }

    var sentencepair = [];
    if (res.blng_sents_part != null && res.blng_sents_part["sentence-pair"]) {
        var sentence_pair = res.blng_sents_part["sentence-pair"];
        for (let i in sentence_pair) {
            let pair = sentence_pair[i];
            sentencepair.push({
                sentence: pair.sentence,
                sentence_eng: pair["sentence-eng"],
                sentence_translation: pair["sentence-translation"],
                source: pair["source"]
            });
        }
    }

    var eetr = [];
    if (res.ee != null && res.ee.word != null) {
        var eetrs = res.ee.word.trs;
        for (let i in eetrs) {
            eetr.push({
                pos: eetrs[i].pos,
                tran: eetrs[i].tr[0].tran
            });
        }
    }

    var synos = [];
    if (res.syno != null && res.syno.synos != null) {
        for (let i in res.syno.synos) {
            let ws = res.syno.synos[i].ws;
            let str = "";
            for (let j in ws) {
                str += (j == 0 ? "" : " / ") + ws[j];
            }
            res.syno.synos[i].ws = str;
        }
        synos = res.syno.synos;
    }

    return {
        web_trans: web_trans, //网络释义
        exam_type: exam_type, //考试类型
        wfs: wfs, //变形
        sentencepair: sentencepair, //双语例句
        ee: eetr,
        synos: synos, //同义词

    };
}

//网易源建议
function getSuggest(words) {
    let res;
    try {
        res = http.get("http://dict.youdao.com/suggest?num=8&doctype=json&q=" + words);
        res = res.body.json();
    } catch(e) {
        log("网络错误：" + e);
    };

    if (res != null && res.data != null && res.data.entries != null)
        return res.data.entries;
    else return [];
}

//金山源
function fromJinshan(words) {
    if (words == "")
        return {
            trs: "", en: "", am: ""
        };
    let res;
    
    try {
        res = http.get("http://dict-co.iciba.com/api/dictionary.php?key=1F9CA812CB18FFDFC95FC17E9C57A5E1&type=json&w= " + words);
        res = res.body.json();
    } catch(e) {
        log("网络错误：" + e);
        return {
            trs: "", en: "", am: ""
        };
    };

    let str = "";
    let ph_en = "",
        ph_am = "",
        ph_en_mp3 = "",
        ph_am_mp3 = "";
    if (res.symbols != null) {
        let symbols = res.symbols[0];
        if (symbols.parts != null) {
            let str2 = "";
            for (let i = 0, n = symbols.parts.length; i < n; i++) {
                let parts = symbols.parts[i];
                if (i > 0) str += "\n";
                if (parts.part == null) {
                    if (parts.part_name != null) {
                        for (let j in parts.means) {
                            str2 += (j == 0 ? "" : "；") + parts.means[j].word_mean;
                        }
                        str += (parts.part_name == "" ? "" : java.lang.String.format("%-4s", parts.part_name)) + str2
                    }
                } else {
                    str2 = getStrFromArray(parts.means);
                    str += (parts.part == "" ? "" : java.lang.String.format("%-4s", parts.part)) + str2;
                }
            }
        }

        if (symbols.ph_en != null)
            ph_en = symbols.ph_en;

        if (symbols.ph_am != null)
            ph_am = symbols.ph_am;

        if (symbols.ph_en_mp3 != null && symbols.ph_en_mp3 != "")
            ph_en_mp3 = symbols.ph_en_mp3;
        else ph_en_mp3 = "http://dict.youdao.com/dictvoice?type=1&audio=" + words;

        if (symbols.ph_am_mp3 != null && symbols.ph_am_mp3 != "")
            ph_am_mp3 = symbols.ph_am_mp3;
        else ph_am_mp3 = "http://dict.youdao.com/dictvoice?type=2&audio=" + words;
    }
    return {
        trs: str,
        en: ph_en,
        am: ph_am,
        en_mp3: ph_en_mp3,
        am_mp3: ph_am_mp3,
    };
}

//网易源
function fromYoudao(words) {
    if (words != null)
        words = String(words).replace(/\s*/g, "");
    if (words == null || words == "")
        return {
            trs: "",
        };
        
    let res;
    try {
        res = http.postJson("http://dict.youdao.com/jsonapi_s?le=&t=1608973762896&sign=534544f64b2073f6b975044912ac60ee&client=mobile&jsonversion=4&keyversion=20171115&userLabel=LEARNER,%20HIGHSCHOOL,%20CET4&abtest=1&keyfrom=mdict.9.0.6.android&vendor=tencent&mid=10&imei=2e48c18f-5e01-483d-8de5-faed3ee21a5d&model=RMX2121&ssid=%3Cunknown+ssid%3E&q=  " + words,
            dicts = {
                "count": 0,
                "dicts": [
                    ["ec"]
                ]
            });
        res = res.body.json();
    } catch(e) {
        log("网络错误：" + e);
        return {
            trs: "",
        };
    };

    let str = "";
    let en = "",
        am = "";
    let en_mp3 = "",
        am_mp3 = "";
    if (res.ec != null && res.ec.word != null) {
        word = res.ec.word;
        
        let trs = word.trs;
        if (trs != null) {
            for (let i = 0; i < trs.length; i++) {
                if (i > 0) str += "\n";
                str += java.lang.String.format("%-4s", trs[i].pos) + trs[i].tran;
            }
        }

        if (word.usphone != null) {
            en = word.usphone;
            en_mp3 = "http://dict.youdao.com/dictvoice?type=1&audio=" + words;
        }

        if (word.ukphone != null) {
            am = word.ukphone;
            am_mp3 = "http://dict.youdao.com/dictvoice?type=2&audio=" + words;
        }
    } else if (res.ce != null && res.ce.word != null) {
        for (let i in res.ce.word.trs) {
            let trs = res.ce.word.trs[i];
            str += (i == 0 ? "" : "\n") + trs["#text"] + "    " + trs["#tran"];
        }
    }

    return {
        trs: str,
        en: en,
        am: am,
        en_mp3: en_mp3,
        am_mp3: am_mp3,
    };
}

function getJinshanMp3(word, type) {
    return type == "en" ? fromJinshan(word).en_mp3 : fromJinshan(word).am_mp3;
}

function getYoudaoMp3(word, type) {
    return type == "en" ? "http://dict.youdao.com/dictvoice?type=1&audio=" + word : "http://dict.youdao.com/dictvoice?type=2&audio=" + word;
}

var networkSource = {
    setSource: function(source) {
        if (source == 0) {
            networkSource.getMeaning = fromJinshan;
            networkSource.getMp3 = getJinshanMp3;
        } else if (source == 1) {
            networkSource.getMeaning = fromYoudao;
            networkSource.getMp3 = getYoudaoMp3;
        }
        networkSource.getSuggest = getSuggest;
    },
    getMeaning: function() {},
    getSuggest: function() {},
    getMoreMeaning: getMoreMeaning,
    threadsSuspend: threadsSuspend,
    getPh: fromJinshan,
};

networkSource.setSource(storages.create("wordbook45qq_setting").get("netFrom", 0));

module.exports = networkSource;